package com.xinxing.city.recovery.ui;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import com.google.gson.reflect.TypeToken;
import com.xinxing.city.recovery.R;
import com.xinxing.city.recovery.RecoveryApplication;
import com.xinxing.city.recovery.entitys.KernelAction;
import com.xinxing.city.recovery.entitys.KernelActions;
import com.xinxing.city.recovery.entitys.SetCategory;
import com.xinxing.city.recovery.net.OkHttpRequest;
import com.xinxing.city.recovery.utils.MyDialog;
import com.xinxing.city.recovery.utils.SharedPreferencesUtils;
import com.xinxing.city.recovery.utils.TextToSpeechManager;

import org.greenrobot.eventbus.EventBus;
import org.w3c.dom.Text;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CompOrderActivity extends AppCompatActivity {
    Gson gson;
    CountDownTimer countDownTimer;
//    MyDialog myDialog = null;
    String orderCode;
    JsonObject resData;
    TextToSpeechManager textToSpeechManager = null;
    private LinearLayout lly ;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comp_order);

        lly = findViewById(R.id.lly_notice);
        gson = new Gson();

        Intent integer =  getIntent();
        orderCode = integer.getStringExtra("orderCode");

        //初始化页面
        initPage();
    }
    //初始化页面
    private void initPage() {

//        //语音
        String ops_putp = (String) SharedPreferencesUtils.getParam(this,"ops_finish","");
        if (!ops_putp.equals("")) {
            JsonObject info = gson.fromJson(ops_putp,JsonObject.class);

            //语音
            String yyStr = "";
            if (info.get("top_ai").getAsString().equals("1")) yyStr += info.get("top_text").getAsString();
            if (info.get("bot_ai").getAsString().equals("1")) yyStr += info.get("bot_text").getAsString();
            if(textToSpeechManager != null) textToSpeechManager.destroy();
            if(!yyStr.equals(""))textToSpeechManager = new TextToSpeechManager(this,yyStr);

            TextView tx1 = findViewById(R.id.text1);
            tx1.setText(info.get("top_text").getAsString());

            TextView tx2 = findViewById(R.id.text2);
            tx2.setText(info.get("bot_text").getAsString());
        }

        //倒计时
        countTimer();

        //获取页面数据
        getOrderDetail();
    }

    //页面加载
    private void orderView(){

        TextView nickName = findViewById(R.id.nickName);
        nickName.setText("交投人："+resData.get("nickName").getAsString());

        TextView userAccount = findViewById(R.id.userAccount);
        String account = resData.get("userAccount").getAsString();
        if (!account.equals("")) {
            if (account.length() > 5) {
                account = account.substring(0,3)+"****"+account.substring(account.length() - 4,account.length());
            }

            userAccount.setText("交投人账号："+account);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        TextView tradingStartTime = findViewById(R.id.tradingStartTime);
        if (resData.get("tradingStartTime") != null || !resData.get("tradingStartTime").getAsString().equals("")) {
            Date date = new Date(resData.get("tradingStartTime").getAsLong() * 1000);
            tradingStartTime.setText("开始时间："+dateFormat.format(date));
        }

        TextView tradingEndTime = findViewById(R.id.tradingEndTime);
        if (resData.get("tradingEndTime") != null || !resData.get("tradingEndTime").getAsString().equals("")) {
            Date date1 = new Date(resData.get("tradingEndTime").getAsLong() * 1000);
            tradingEndTime.setText("结束时间："+dateFormat.format(date1));
        }

        TextView recycleCataName = findViewById(R.id.recycleCataName);
        recycleCataName.setText("交投品类："+resData.get("recycleCataName").getAsString());

        TextView weight = findViewById(R.id.weight);
        weight.setText("交投重量："+resData.get("weight").getAsString()+"kg");
        String price =resData.get("pkgPrice").getAsString();
        if(!price.equals("")){
            if(price.contains(".")){
                String[] strs = price.split("\\.");
                String s=strs[0]+".";
                if(strs[1].length()<=2){
                    if(strs[1].length()==1){
                        s += strs[1]+"0";
                    }else if(strs[1].length()==2){
                        s += strs[1];
                    }

                }else{
                    s+= strs[1].substring(0,2);
                }
                price = s;
            }else{
                price = price+".00";
            }
        }
        TextView pkgPrice = findViewById(R.id.pkgPrice);
        if(pkgPrice!=null&&price!=null) {
            pkgPrice.setText("品类单价：" + price + "/kg");
        }
        TextView orderCompletedTime = findViewById(R.id.orderCompletedTime);
        if (resData.get("tradingEndTime") != null || resData.get("tradingEndTime").getAsInt() != 0) {
            Date date2 = new Date(resData.get("tradingEndTime").getAsLong() * 1000);
            orderCompletedTime.setText("结算完成时间："+dateFormat.format(date2));
        }

        TextView amount = findViewById(R.id.amount);
        String examount = resData.get("expectAmount").getAsString();
        if(!examount.equals("")) {
            if(examount.contains(".")){
                String[] strs = examount.split("\\.");
                String s=strs[0]+".";
                if(strs[1].length()<2){
                    s += strs[1];
                }else{
                    s+= strs[1].substring(0,2);
                }
                amount.setText("预计可得：" + s);
            }else{
                amount.setText("预计可得：" + resData.get("expectAmount").getAsString());
            }
        }else{
            amount.setText("预计可得：" + "0.00");
        }
    }

    //继续交投
    public void conBtn(View view) {
        EventBus.getDefault().post(new KernelAction(KernelActions.CREAT_ORDER, null));
        finish();
    }

    //退出
    public void outBtnRes(View view) {
//        RecoveryApplication.getInstance().setToken("");
        finish();
    }

    /*倒计时*/
    private void countTimer() {
        // 设置倒计时的总时间（单位：毫秒）
        int totalTime = 10000;

        String str = (String) SharedPreferencesUtils.getParam(this,"ops_finish","");
        if(!str.equals("")){
            Type dev = new TypeToken<SetCategory>() {}.getType();
            Gson gson = new Gson();;
            SetCategory setCategory = gson.fromJson(str,dev);
            if(!setCategory.getAutoOutTime().equals("")) {
                totalTime = Integer.valueOf(setCategory.getAutoOutTime())*1000;
            }
        }

        // 设置倒计时的间隔时间（单位：毫秒）
        int interval = 1000;
        Button button = findViewById(R.id.outBtn);

        countDownTimer = new CountDownTimer(totalTime, interval) {
            @Override
            public void onTick(long millisUntilFinished) {
                long seconds = millisUntilFinished / 1000;
                button.setText("退出("+(String.valueOf(seconds))+"s)"); // 更新TextView显示的时间
            }
            @Override
            public void onFinish() {
                outBtnRes(findViewById(R.id.outBtn));
            }
        };
        countDownTimer.start();
    }

    /********************************* 数据 *************************************/
    //获取订单详情
    private void getOrderDetail() {

        String ops_putp = (String) SharedPreferencesUtils.getParam(this,"ops_settlement","");
        JsonObject info = null;
        if (!ops_putp.equals("")) {
            info = gson.fromJson(ops_putp,JsonObject.class);
            if (!info.get("text").getAsString().equals("")) {
                lly.setVisibility(View.VISIBLE);
                textView.setText(info.get("text").getAsString());
//                myDialog = MyDialog.newInstance("提示",info.get("text").getAsString(),"","");
//                myDialog.show(getSupportFragmentManager(),"MyDialog");
            }
        } else {
            lly.setVisibility(View.VISIBLE);
            textView.setText("正在结算中...");

        }

        OkHttpRequest okHttpRequest = new OkHttpRequest(this,getSupportFragmentManager());
        okHttpRequest.sendGetRequest("/sr-recycling/v1/01/recycle/trad_order/get?code="+orderCode, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                lly.setVisibility(View.GONE);
                Log.e("dsfsdf1",e.getMessage());
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                lly.setVisibility(View.GONE);
                JsonObject resData1 = okHttpRequest.getResData();
                Log.d("CompOrderActivity","接口："+resData1.toString());
                if (resData1 == null) return ;

                resData = resData1.get("data").getAsJsonObject();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        orderView();
                    }
                });

            }
        });

    }




}
